package main

import (
	"fmt"
	"github.com/BurntSushi/toml"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"net/http"
	"os"
	"short-link/model"
	"short-link/util"
	"time"
)

func main() {
	err := loadConfig()
	if err != nil {
		util.Error("配置加载失败 %v", err)
		return
	}
	handler, err := NewHttpHandler()
	if err != nil {
		util.Error("服务初始化失败 %v", err)
		return
	}
	util.Debug("启动服务 8080")
	err = http.ListenAndServe(":8080", handler)
	if err != nil {
		util.Error("服务启动失败 %v", err)
		return
	}
}

type HttpHandler struct {
	db *gorm.DB
}

func NewHttpHandler() (h *HttpHandler, err error) {
	h = &HttpHandler{}
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // 日志级别
			Colorful:      false,       // 禁用彩色打印
		},
	)
	{ //  初始化数据库
		dsn := model.AppConfig.Database.Url
		h.db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
			Logger: newLogger,
		})
		if err != nil {
			return nil, err
		}
	}
	return h, nil
}

func (h *HttpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	NewHandler(h, w, r).handle()
}

func loadConfig() error {
	env := os.Getenv("ENV")
	if len(env) > 0 {
		env = fmt.Sprintf(".%s", env)
	}
	configFile := fmt.Sprintf("./resources/application%s.toml", env)
	util.Debug("加载配置文件 %s", configFile)
	if _, err := toml.DecodeFile(configFile, &model.AppConfig); err != nil {
		return err
	}
	return nil
}
